package com.abc.model;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.ai.chat.messages.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 聊天消息实体类
 * 用于MongoDB持久化存储
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "chat_messages")
public class ChatMessageModel {

    @Id
    private String id;

    @Field("message_id")
    private String messageId;

    /**
     * 对话ID
     */
    @Field("session_id")
    private String sessionId;

    @Field("username")
    private String username;

    /**
     * 消息类型：user/assistant/system
     */
    @Field("message_type")
    private String messageType;

    /**
     * 消息内容
     */
    @Field("content")
    private String content;

    /**
     * 创建时间
     */
    @Field("create_time")
    private LocalDateTime createTime;


    /**
     * 额外的元数据（JSON格式）
     */
    @Field("metadata")
    private String metadata;

    /**
     * 父消息ID：指向上一条相关消息的ID
     */
    @Field("parent_message_id")
    private String parentMessageId;

    /**
     * 消息链路：存储从根消息到当前消息的链路（包含当前消息）
     */
    @Field("message_chain")
    private List<String> messageChain;


    public ChatMessageModel(String sessionId, String messageType, String username, String content, String messageId, Map<String, Object> metadata, String parentMessageId, List<String> messageChain) {
        this.sessionId = sessionId;
        this.messageType = messageType;
        this.content = content;
        this.messageId = messageId;
        this.createTime = LocalDateTime.now();
        this.username = username;
        this.metadata = JSON.toJSONString(metadata);
        this.parentMessageId = parentMessageId;
        this.messageChain = messageChain;
    }

    public static Message toMessage(ChatMessageModel ChatMessageModel) {
        String messageTypeStr = ChatMessageModel.getMessageType();
        if (ObjectUtil.isEmpty(messageTypeStr)) {
            return null;
        }

        MessageType messageType = MessageType.fromValue(messageTypeStr);
        return switch (messageType) {
            case SYSTEM -> SystemMessage.builder().text(ChatMessageModel.getContent()).build();
            case USER -> UserMessage.builder().text(ChatMessageModel.getContent()).build();
            case ASSISTANT -> new AssistantMessage(ChatMessageModel.getContent());
            default -> null;
        };
    }


}
